package com.GB26875_3_2011.codec;

import com.GB26875_3_2011.util.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.util.List;

/**
 * @author 蒋仕国
 * @projectName GB26875_3_211
 * @ClassName StartAndEndSymbolsDecoder
 * @date 2025-01-10 15:44
 * @Description: TODO [开始符号，结束符号处理器，处理结果还是一个butef]
 */
public class StartAndEndSymbolsCodec extends ByteToMessageCodec<ByteBuf> {

    private final byte[] startFlag;
    private final byte[] endFlag;
    private final long minLength;


    public StartAndEndSymbolsCodec(byte[] startFlag, byte[] endFlag, long minLength) {
        this.startFlag = startFlag;
        this.endFlag = endFlag;
        this.minLength = minLength;
    }

    public StartAndEndSymbolsCodec(byte[] startFlag, byte[] endFlag) {
        this.startFlag = startFlag;
        this.endFlag = endFlag;
        this.minLength = startFlag.length + endFlag.length;
    }




    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
        out.writeBytes(startFlag);
        out.writeBytes(msg);
        out.writeBytes(endFlag);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 已经处理掉了前缀后缀
        if (in.readableBytes() <= minLength) {
            // 检查是否有足够的字节来读取长度前缀
            return;
        }
        ByteBuf buffer = Unpooled.buffer((int) (in.readableBytes() - minLength));
        // 读取到前缀
        ByteUtils.readSomeByte(startFlag.length, in);
        byte[] bytes = ByteUtils.readSomeByte(in.readableBytes() - endFlag.length, in);
        buffer.writeBytes(bytes);
        out.add(buffer);
        in.clear();
    }

}
